package com.bbs.imp3;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;


/**
 * WebView
 * @author songdehuai
 */
public class WebActivity extends AppCompatActivity {

    WebView webview;

    String Url = "http://bbs.imp3.net/forum.php?mobile=yes";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);
        initTitle();
        initWbeView();

    }

    ImageView titleLeft;
    TextView titleText;

    void initTitle() {
        webview = (WebView) findViewById(R.id.webview);
        titleLeft = (ImageView) findViewById(R.id.title_left);
        titleText = (TextView) findViewById(R.id.title_text);
        titleLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (webview.getUrl().equals(Url)) {
            super.onBackPressed();
        } else {
            webview.goBack();
        }
    }

    /**
     * 初始化webView
     */
    void initWbeView() {
        assert webview != null;
        WebSettings settings = webview.getSettings();
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setJavaScriptEnabled(true);

        webview.addJavascriptInterface(WebActivity.this, "android");

        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                titleText.setText(webview.getTitle());
            }


            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.indexOf("http") == 0 || url.indexOf("https") == 0 || url.indexOf("www") == 0) {
                    view.loadUrl(url);
                }
                return true;
            }


            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {

            }
        });


        webview.loadUrl(Url);
    }

    @JavascriptInterface
    public void startFunction() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                finish();
            }
        });
    }

    @JavascriptInterface
    public void startFunction(String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                finish();
            }
        });
    }

}
